package com.qiguliuxing.dts.db.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.qiguliuxing.dts.db.dao.DtsStorageMapper;
import com.qiguliuxing.dts.db.domain.DtsStorage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DtsStorageService {
	@Autowired
	private DtsStorageMapper storageMapper;

	public void deleteByKey(String key) {
		QueryWrapper<DtsStorage> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsStorage::getKey, key);
		storageMapper.delete(queryWrapper);
	}

	public void add(DtsStorage storageInfo) {
		storageInfo.setAddTime(LocalDateTime.now());
		storageInfo.setUpdateTime(LocalDateTime.now());
		storageMapper.insert(storageInfo);
	}

	public DtsStorage findByKey(String key) {
		QueryWrapper<DtsStorage> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsStorage::getKey, key);
		queryWrapper.lambda().eq(DtsStorage::getDeleted, false);
		return storageMapper.selectOne(queryWrapper);
	}

	public int update(DtsStorage storageInfo) {
		storageInfo.setUpdateTime(LocalDateTime.now());
		return storageMapper.updateById(storageInfo);
	}

	public DtsStorage findById(Integer id) {
		return storageMapper.selectById(id);
	}

	public List<DtsStorage> querySelective(String key, String name, Integer page, Integer limit, String sort,
			String order) {
		QueryWrapper<DtsStorage> queryWrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(key)) {
			queryWrapper.lambda().eq(DtsStorage::getKey, key);
		}
		if (StrUtil.isNotEmpty(name)) {
			queryWrapper.lambda().like(DtsStorage::getName, name);
		}
		queryWrapper.lambda().eq(DtsStorage::getDeleted, false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
			queryWrapper.orderByDesc(sort);
		}
		IPage<DtsStorage> iPage = new Page<>(page, limit);

		return storageMapper.selectPage(iPage, queryWrapper).getRecords();
	}
}
